package top.oylan.manager.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.oylan.manager.entity.*;
import top.oylan.manager.entity.example.CategoryExample;
import top.oylan.manager.service.CategoryService;
import top.oylan.manager.service.ProductService;
import top.oylan.manager.service.SectionService;
import top.oylan.manager.tools.*;
import top.oylan.manager.tools.enums.Types;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-04-02
 */
@Controller
@RequestMapping("/admin/movie")
public class AdminMovieController {

    @Resource
    ProductService productService;

    @Resource
    SectionService sectionService;

    @Resource
    CategoryService categoryService;

    @Resource
    FileUploader fileUploader;

    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String index(ModelMap modelMap,@RequestParam(value = "page",defaultValue = "1")Integer page){

        Pager pager = new Pager();
        pager.setCurrentPage(page);
        Video condition = new Video();
        pager.setCondition(condition);
        List<Video> list = productService.selectMovieByPager(pager);
        pager.setList(list);
        modelMap.addAttribute("pager",pager);
        return  "admin/movie/list";
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(ModelMap modelMap){
        setCategories(modelMap);
        return "admin/movie/add";
    }

    private void setCategories(ModelMap modelMap) {

        List<Category> categories = categoryService.selectCategoriesForProduct(Types.MOVIE_NOTICE);
        modelMap.addAttribute("categories",categories);
    }


    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public String edit(ModelMap modelMap,@RequestParam Integer id){
        setCategories(modelMap);
        Course product = productService.selectProductById(id);
        Section condition = new Section();
        condition.setProductId(id);
        condition.setParentId(-1);
        condition.setLv((byte)2);
        List<Section> videos = sectionService.selectSectionsByCondition(condition);
        modelMap.addAttribute("movie",product);
        modelMap.addAttribute("videos",videos);
        return "admin/movie/edit";
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody JSONObject movieJson){

        Result result = new Result();
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        JSONArray videos = movieJson.getJSONArray("videos");

        Product product = new Product();
        product.setType((movieJson.getByte("type")));
        product.setTitle(movieJson.getString("title"));
        product.setCateId(movieJson.getShort("cateId"));
        product.setStatus(movieJson.getByte("status"));
        product.setCreateTime(new Date());
        product.setContent(movieJson.getString("content"));
        product.setDescription(movieJson.getString("description"));
        if(videos.size() == 1){
            product.setScope((byte)1);
        }else{
            product.setScope((byte)2);
        }
        product.setPicture(movieJson.getString("picture"));
        product.setThumb(movieJson.getString("thumb"));
        product.setAuthorId(user.getId().shortValue());
        int insert = productService.addProduct(product);
        if(insert > 0){
            for(int i=0;i<videos.size();i++){
                Section section = new Section();
                JSONObject video = videos.getJSONObject(i);
                section.setProductId(product.getId());
                section.setParentId(-1);
                section.setVedioUrl(video.getString("url"));
                section.setTitle(video.getString("title"));
                section.setLv((byte)2);
                section.setCreateTime(new Date());
                sectionService.saveSection(section);
            }
            result.setMessage("添加成功");
        }
        return result;
    }


    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestBody JSONObject jsonObject){
        Result result = new Result();
        JSONObject object = new JSONObject();
        object.put("productId",jsonObject.get("id"));
        object.put("id",-1);
        object.put("videos",jsonObject.getJSONArray("videos"));

        jsonObject.remove("videos");

        Product product =  JSONObject.parseObject(jsonObject.toJSONString(),Product.class);
        productService.updateProduct(product);

        jmsMessagingTemplate.convertAndSend("queue.update_section_video",object.toJSONString());
        result.setCode((byte) 1);
        result.setMessage("更新成功");
        return result;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file){
        JSONObject obj = new JSONObject();
        Result res = fileUploader.upload(file, Directory.ART);
        if(res.getCode() == 1){
            obj.put("path",res.getData().get("path").toString());
            obj.put("status",1);
        }else{
            obj.put("status",1);
        }
        return obj;
    }

    @RequestMapping(value = "/file/remove",method = RequestMethod.GET)
    public Result unlink(@RequestParam(value = "path")String path){

        Result result = new Result((byte) 1,"成功");
        fileUploader.removeFile(SystemConstants.UPLOAD_ROOT_PATH+path);
        return result;
    }
}
